import json
import urllib.parse
import urllib.request as request
import urllib.error as error
import requests

def get_war():
    city_code = "410100"
    key = "c5599bd0875a71b01aad5ffb802c3fc3"
    api_url = "http://apis.juhe.cn/fapig/alarm/queryV2"
    params_dict = {
        "city_code": city_code,  # 查询天气的城市名称，如：北京、苏州、上海
        "key": key,  # 您申请的接口API接口请求Key
    }
    params = urllib.parse.urlencode(params_dict)
    try:
        req = request.Request(api_url, params.encode())
        response = request.urlopen(req)
        content = response.read()
        if content:
            try:
                result = json.loads(content)
                # print(result)
                error_code = result['error_code']
                print(error_code)
                if error_code == 0:
                    i = 0
                    title_name = "无预警信息"
                    sky_type = " "
                    if result['result'] is not None:
                        for i in range(len(result["result"])):
                            if "郑州" in result["result"][i]['title']:
                                title_name = result["result"][i]['title']
                                sky_type = result["result"][i]['type']
                                break
                        title_name = "## 今日预警信息：" + "⚠️" + title_name + "⚠️" + "\n\n" + "---" + "\n\n"
                    return title_name, sky_type
                else:
                    print("请求失败:%s %s" % (result['error_code'], result['reason']))
            except Exception as e:
                print("解析结果异常：%s" % e)
        else:
            # 可能网络异常等问题，无法获取返回内容，请求异常
            print("请求异常")
    except error.HTTPError as err:
        print(err)
    except error.URLError as err:
        # 其他异常
        print(err)

if __name__ == "__main__":
    get_war()